<template>
  <div class="login-container">
    <div class="login-form" v-if="!isLoggedIn">
      <h2 style="color: aliceblue;">登录</h2>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="form.password" show-password placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button v-hasPermi="['loginForm:loginForm:query']" type="primary" @click="submitForm('form')">立即登录</el-button>
        </el-form-item>
      </el-form>
      <p class="register-link">
        <el-checkbox v-model="isAgreed" style="margin-top: 10px;" value="Online activities" name="type">
          同意
        </el-checkbox>
        没有账号？
        <a href="#/Register" :class="{ disabled: !isAgreed }" @click.prevent="handleRegisterClick">
          立即注册
        </a>
      </p>
    </div>
    <div class="user-info" v-else>
      <h2 style="color: aliceblue;">欢迎，{{ username }}</h2>
      <el-button type="primary" @click="logout">注销</el-button>
    </div>
  </div>
</template>
<script>
import axios from 'axios';

export default {
  data() {
    return {
      form: {
        username: '',
        password: '',
        isAgreed: false,
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ]
      },
      isLoggedIn: false,
      username: ''
    };
  },
  methods: {
    handleRegisterClick() {
      if (this.isAgreed) {
        this.$router.push('/Register');
      } else {
        alert('请先同意条款');
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const loginData = {
            username: this.form.username,
            password: this.form.password
          };

          axios.post('http://localhost:8090/user/login', loginData)
            .then(response => {
              console.log("data=", response);
              if (response.data.code === 200) {
                // 登录成功，保存 token 和用户名
                localStorage.setItem('token', response.data.token);
                localStorage.setItem('username', this.form.username);
                this.isLoggedIn = true;
                this.username = this.form.username;
               this.$router.push('/EducationHome');
              } else {
                console.error('登录失败:', response.data.message);
                alert('登录失败，请检查用户名和密码');
              }
            })
            .catch(error => {
              console.error('请求失败:', error);
              alert('请求失败，请稍后再试');
            });
        } else {
          console.log('表单验证失败！');
          return false;
        }
      });
    },
    logout() {
      // 注销操作，清除 token 和用户名
      localStorage.removeItem('token');
      localStorage.removeItem('username');
      this.isLoggedIn = false;
      this.username = '';
      this.$router.push('/LoginForm');
    }
  },
  created() {
    // 检查是否已经登录
    const token = localStorage.getItem('token');
    const username = localStorage.getItem('username');
    if (token &&username) {
      this.isLoggedIn = true;
      this.username = username;
    }
  }
};
</script>
<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 93.5vh;
  background: #ecfeff;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  background-image: url('../assets/33.png'); /* 替换为你的图片路径 */
  background-size: cover; /* 使背景图像覆盖整个元素 */
  background-position: center; /* 使背景图像居中 */
}

.login-form {
  background: rgba(144, 97, 118, 0.167);
  padding: 20px;
  border-radius: 9px;
  box-shadow: 0 5px 7px rgba(246, 247, 247, 0.852);
  width: 300px;
}

.user-info {
  background: rgba(144, 97, 118, 0.167);
  padding: 20px;
  border-radius: 9px;
  box-shadow: 0 5px 7px rgba(246, 247, 247, 0.852);
  width: 300px;
  text-align: center;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.register-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #666;
}

.register-link a {
  color: #409eff;
  text-decoration: none;
}

.register-link a:hover {
  text-decoration: underline;
}
</style>
